package com.bdqn.springbootshior.service.impl;

import com.bdqn.springbootshior.entity.Role;
import com.bdqn.springbootshior.entity.User;
import com.bdqn.springbootshior.repository.UsrRepository;
import com.bdqn.springbootshior.service.UsrService;
import jakarta.annotation.Resource;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class UsrServiceImpl implements UsrService {

    @Resource
    private UsrRepository usrRepository;

    public UsrServiceImpl(UsrRepository usrRepository) {
        this.usrRepository = usrRepository;
    }


    @Override
    public Page<User> findPageByMap(Map param, Pageable pageable) {
        return usrRepository.findAll((Specification<User>) (root, query, cb) -> {
            List<Predicate> list = new ArrayList<>();
            if (param.get("usrName") != null) {
                list.add(cb.like(root.get("usrName"), "%" + param.get("usrName") + "%"));
            }
            if (param.get("usrRoleId") != null) {
                list.add(cb.equal(root.get("usrRoleId"), param.get("usrRoleId")));
            }

            return cb.and(list.toArray(new Predicate[list.size()]));
        }, pageable);
    }


    public Page<User> findByUsrNameAndUsrRoleId(String usrName, Long usrRoleId, Pageable pageable) {
        Specification<User> specification = new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();
                if (usrName != null && !"".equals(usrName)) {
                    list.add(cb.like(root.get("usrName"), "%" + usrName + ("usrName") + "%"));
                }
                if (usrRoleId != null && usrRoleId.longValue() != 01) {
                    Role role = new Role();
                    role.setRoleId(usrRoleId);

                    list.add(cb.equal(root.get("usrRoleId"), usrRoleId));
                }

                return cb.and(list.toArray(new Predicate[list.size()]));
            }
        };
        return usrRepository.findAll(specification, pageable);
    }



//    public User getUserByUsrName(String usrName) {
//        return  usrRepository.findUserByUsrName(usrName);
//    }
}
